// member/pages/memberCard/memberCard.js
let myRequest = require('../../common/script/myRequest.js');
let api = require('../../common/script/api.js');
let login = require('../../common/script/login');
let app = getApp()
var timeOut = null //倒计时函数
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userName: '',
    userPhone: '',
    isVip: true,
    isfoundingmember: false,
    selectAddressData: [],
    toggle: false,
    phone: '',
    phone_sign: '',
    address: '',
    phoneToggle: false,
    phoneTime: 60,
    phoneCodeShow: true,
    smsCode: '',
    time: 3000,
  },
  getRefreshMember(encrypt_str = '') {
    let that = this;
    let data = {
      encrypt_str,
      cardnumber: that.data.cardnumber,
      type: 1
    }
    clearTimeout(timeOut)
    myRequest.EasyHttp.post(api.reqUrls.refreshMember, data).then(res => {
      if (res.data.status == 1) {
        that.setData({
          time: res.data.result.interval * 1000,
        })
        if (res.data.result.refreshCard) {
          that.getCardinfoData()
          clearTimeout(timeOut)
        } else {
          timeOut = setTimeout(() => {
            that.getRefreshMember()
          }, that.data.time)
        }

      } else if (res.data.status == -2) {
        my.hideLoading();

      } else {
        my.showToast({
          content: res.data.msg,
          type: 'exception',
        })
      }
    })
  },
  //获取手机号验证码
  phoneCode() {
    const that = this;
    if (that.data.phone.length == 11) {
      let data = {
        appid: my.getAppIdSync().appId,
        phone: that.data.phone,
        cardnumber: '',
        openId: my.getStorageSync({
          key: 'openId'
        }).data,
      }
      my.showLoading({
        title: '加载中...',
      })
      myRequest.EasyHttp.post(api.reqUrls.AlipayMemberCardBindSendSMSCode, data).then(res => {
        my.hideLoading()
        if (res.data.data.success == true) {
          my.showToast({
            content: '验证码发送成功',
            type: 'success',
          })
          that.setData({
            phoneCodeShow: false,
          })
          let time = setInterval((() => {
            if (that.data.phoneTime == 1) {
              clearInterval(time)
              that.setData({
                phoneCodeShow: true,
                phoneTime: 60
              })
            } else {
              that.setData({
                phoneCodeShow: false,
                phoneTime: that.data.phoneTime - 1
              })
            }
          }), 1000)
        } else {
          my.showModal({
            showCancel: false,
            content: res.data.data.msg,
            success(res) {
              if (res.confirm) {

              }
            }
          })
        }
      }).catch(err => {
        console.log(err, 888)
      })
    } else {
      my.showToast({
        content: '手机号格式错误',
        type: 'exception',
      })
    }


  },
  getPhoneCode(e) {
    const that = this;
    that.setData({
      smsCode: e.detail.value
    })
  },
  getPhone(e) {
    const that = this;
    that.setData({
      phone: e.detail.value
    })
  },
  // 显示手机弹窗
  onPhoneToggle() {
    const that = this;
    that.setData({
      phoneToggle: true
    })
  },
  // 关闭手机弹窗
  onClosePhoneToggle() {
    const that = this;
    that.setData({
      phoneToggle: false,
      phoneCodeShow: true,
      phoneTime: 60
    })
  },
  //手机号验证
  bindBySms() {
    const that = this;
    if (!that.data.phone) {
      my.showToast({
        content: '请输入手机号码',
        type: 'exception',

      })
      return
    }
    if (!that.data.smsCode) {
      my.showToast({
        content: '请输入验证码',
        type: 'exception',

      })
      return
    }
    let data = {
      appid: my.getAppIdSync().appId,
      openId: my.getStorageSync({
        key: 'openId'
      }).data,
      phone: that.data.phone,
      checkcode: that.data.smsCode,
    }
    my.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.AlipayMemberCardBindCheckSMSCode, data).then(res => {
      my.hideLoading()
      console.log(res, 898989)
      if (res.data.data.success == true) {
        that.onClosePhoneToggle()
        that.setData({
          phoneCodeShow: true,
          phoneTime: 60
        })
        let stringArray = res.data.data.cards.map(item => `${item.cardnumber} 余额￥${item.totalamount}`);
        // 弹出选择卡号对话框
        my.optionsSelect({
          title: "选择绑定卡号",
          optionsOne: stringArray,
          positiveString: "立即绑定",
          success(prop) {
            console.log(prop, 9999)
            if (prop.selectedOneIndex !== "") {
              console.log(123)
              let cardnumber = res.data.data.cards[prop.selectedOneIndex].cardnumber
              that.bindCardNumber(cardnumber, 1)
            }
          }
        });
      } else {
        my.showModal({
          showCancel: false,
          content: res.data.data.msg,
          success(res) {
            if (res.confirm) {

            }
          }
        })
      }

    })
  },

  //获取会员信息
  getCardinfoData() {
    const that = this;
    my.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.membercardShow).then(res => {
      my.stopPullDownRefresh();
      my.hideNavigationBarLoading();
      my.hideLoading();
      if (res.data.status == 1) {
        that.setData({
          isfoundingmember: res.data.result.member_data.isfoundingmember,
          isVip: true,
          totalamount: res.data.result.member_data.totalamount,
          cardnumber: res.data.result.member_data.cardnumber,
          userName: res.data.result.member_data.name,
          userPhone: res.data.result.member_data.phone,
        })
        my.setStorageSync({
          key: 'isVip',
          data: true
        })
        my.setStorageSync({
          key: 'refresh',
          data: false
        })
        my.setStorageSync({
          key: 'isfoundingmember',
          data: res.data.result.member_data.isfoundingmember
        })
        my.setStorageSync({
          key: 'cardnumber',
          data: res.data.result.member_data.cardnumber
        })
        my.setStorageSync({
          key: 'totalamount',
          data: res.data.result.member_data.totalamount
        })
        my.setStorageSync({
          key: 'userName',
          data: res.data.result.member_data.name
        })
        my.setStorageSync({
          key: 'userPhone',
          data: res.data.result.member_data.phone
        })
      } else if (res.data.status == -2) {
        my.setStorageSync({
          key: 'isVip',
          data: false
        })
        my.setStorageSync({
          key: 'refresh',
          data: false
        })
        my.setStorageSync({
          key: 'isfoundingmember',
          data: false
        })
        my.setStorageSync({
          key: 'cardnumber',
          data: ''
        })
        my.setStorageSync({
          key: 'totalamount',
          data: 0
        })
        my.setStorageSync({
          key: 'userName',
          data: ''
        })
        my.setStorageSync({
          key: 'userPhone',
          data: ''
        })
        that.setData({
          isVip: false,
          isfoundingmember: false,
          totalamount: 0,
          cardnumber: '',
          userName: "",
          userPhone: ""
        })

      }
    })
  },

  //充值金额
  toTecharge() {
    const that = this;
    if (!that.data.isVip) {
      my.showToast({
        content: '请绑定会员卡',
        type: 'exception',

      })
      return
    }
    clearTimeout(timeOut)
    my.navigateTo({
      url: `/member/pages/recharge/recharge`,
    })
  },
  //付款
  toPayment() {
    const that = this;
    if (!that.data.isVip) {
      my.showToast({
        content: '请绑定会员卡',
        type: 'exception',

      })
      return
    }
    clearTimeout(timeOut)
    my.switchTab({
      url: '/pages/index/index'
    })
  },
  //优惠券
  toCoupon() {
    const that = this;
    if (!that.data.isVip) {
      my.showToast({
        content: '请绑定会员卡',
        type: 'exception',

      })
      return
    }
    clearTimeout(timeOut)
    my.navigateTo({
      url: `/member/pages/coupon/coupon`,
    })
  },
  //充值记录
  toRechargeRecord() {
    const that = this;
    if (!that.data.isVip) {
      my.showToast({
        content: '请绑定会员卡',
        type: 'exception',

      })
      return
    }
    clearTimeout(timeOut)
    my.navigateTo({
      url: `/member/pages/rechargeRecord/rechargeRecord`,
    })
  },
  // 消费记录
  toSpending() {
    const that = this;
    if (!that.data.isVip) {
      my.showToast({
        content: '请绑定会员卡',
        type: 'exception',

      })
      return
    }
    clearTimeout(timeOut)
    my.navigateTo({
      url: `/member/pages/spending/spending`,
    })
  },
  toPark() {
    const that = this;
    if (!that.data.isVip) {
      my.showToast({
        content: '请绑定会员卡',
        type: 'exception',
      })
      return
    }
    clearTimeout(timeOut)
    my.navigateTo({
      url: `/member/pages/park/park`,
    })
  },
  //礼品券审核
  toGiftCoupon() {
    const that = this;
    if (!that.data.isVip) {
      my.showToast({
        content: '请绑定会员卡',
        type: 'exception',
      })
      return
    }
    clearTimeout(timeOut)
    my.navigateTo({
      url: `/member/pages/giftCoupon/giftCoupon`,
    })
  },
  //线下订单
  toOfflineOrder() {
    const that = this;
    if (!that.data.isVip) {
      my.showToast({
        content: '请绑定会员卡',
        type: 'exception',

      })
      return
    }
    clearTimeout(timeOut)
    my.navigateTo({
      url: `/member/pages/offlineOrder/offlineOrder`,
    })
  },
  // 会员卡详情
  toCardDetail() {
    const that = this;
    if (!that.data.isVip) {
      my.showToast({
        content: '请绑定会员卡',
        type: 'exception',

      })
      return
    }
    clearTimeout(timeOut)
    my.navigateTo({
      url: `/member/pages/cardDetail/cardDetail`,
    })
  },
  //更换会员卡
  toSwapCard() {
    const that = this;
    if (!that.data.isVip) {
      my.navigateTo({
        url: `/member/pages/swapCard/swapCard`,
      })
    } else {
      my.showModal({
        title: '换卡确认',
        content: '确认解除当前绑定的储值卡，并重新绑定其他储值卡吗？',
        success: (prop) => {
          console.log(prop);
          if (prop.confirm) {
            let data = {
              appid: my.getAppIdSync().appId,
              cardnumber: that.data.cardnumber,
              openId: my.getStorageSync({
                key: 'openId'
              }).data,
            }
            my.showLoading({
              title: '加载中...',
            })
            myRequest.EasyHttp.post(api.reqUrls.AlipayMemberCardUnbind, data).then(res => {
              my.hideLoading();
              if (res.data.data.success == true) {
                my.setStorageSync({
                  key: 'isVip',
                  data: false
                })
                my.setStorageSync({
                  key: 'refresh',
                  data: false
                })
                my.setStorageSync({
                  key: 'isfoundingmember',
                  data: false
                })
                my.setStorageSync({
                  key: 'cardnumber',
                  data: ''
                })
                my.setStorageSync({
                  key: 'totalamount',
                  data: 0
                })
                my.setStorageSync({
                  key: 'userName',
                  data: ''
                })
                my.setStorageSync({
                  key: 'userPhone',
                  data: ''
                })
                that.setData({
                  isVip: false,
                  isfoundingmember: false,
                  totalamount: 0,
                  cardnumber: '',
                  userName: '',
                  userPhone: ''
                })
                my.showModal({
                  content: res.data.data.msg,
                  showCancel: false,
                  success() {
                    my.navigateTo({
                      url: `/member/pages/swapCard/swapCard`,
                    })
                  }
                })
              } else {
                console.log(2222)
                my.showModal({
                  content: res.data.data.msg,
                  showCancel: false,
                  confirmText: '我知道了',
                  confirmColor: '#ff5151',
                  success(e) {}
                })
              }
            })
          }
        },
        fail: (err) => {
          console.log(err);
        }
      })
    }

  },

  //绑定手机号
  getPhoneNumber(e) {
    const that = this;
    my.getPhoneNumber({
      success: (res) => {
        let data = {
          appid: my.getAppIdSync().appId,
          phoneEncryptedData: res.response,
        }
        my.showLoading({
          title: '加载中...',
        })
        myRequest.EasyHttp.post(api.reqUrls.getBindMemberCardPhone, data).then(res => {
          if (res.status == 200) {
            // that.applyVirtual(res.data.data)
            that.setData({
              phone: res.data.data,
            })
            // that.getSite()
            that.applyVirtual()
          } else {
            my.hideLoading();
            my.showModal({
              showCancel: false,
              content: res.data.errormsg,
              success(res) {
                if (res.confirm) {

                }
              }
            })
          }
        })
      }
    })
  },
  getSite() {
    const that = this;
    myRequest.EasyHttp.post(api.reqUrls.getRegisterMemberSelectAddress).then(res => {
      my.hideLoading();
      if (res.data.status == 1) {
        that.setData({
          selectAddressData: res.data.result.address
        })
        that.onToggle()
      }

    })
  },
  // 显示弹窗
  onToggle() {
    const that = this;
    that.setData({
      toggle: true
    })
  },
  // 关闭弹窗
  onCloseToggle() {
    const that = this;
    that.setData({
      toggle: false,
    })
  },
  bindSelectAddress(e) {
    const that = this;
    let index = e.detail.value[0]
    that.setData({
      address: that.data.selectAddressData[index]
    })
    console.log(e, 888)
  },
  // 申请会员卡
  applyVirtual() {
    const that = this;
    that.onCloseToggle()
    let phone = that.data.phone;
    let address = that.data.address;
    let data = {
      phone,
      appid: my.getAppIdSync().appId,
      OpenId: my.getStorageSync({
        key: 'openId'
      }).data,
      address
    }
    my.showLoading({
      title: '加载中...',
    })
    console.log(3333)
    myRequest.EasyHttp.post(api.reqUrls.CheckAlipaySendNewCard, data).then(res => {
      if (res.data.data.code == 200) {
        that.applyCard()
      } else if (res.data.data.code == 10001) {
        console.log(4444)
        my.hideLoading();
        let params = {
          appid: my.getAppIdSync().appId,
          openId: my.getStorageSync({
            key: 'openId'
          }).data
        }
        myRequest.EasyHttp.post(api.reqUrls.getAlipayMemberCardBindStatus, params).then(prop => {

          var templateid = prop.data.data.templateid;
          if (!prop.data.data.isalipaycard) {
            // 弹出半屏开卡
            that.startOpenCard(templateid, my.getAppIdSync().appId, my.getStorageSync({
              key: 'openId'
            }).data);
          }
        })

      } else {
        console.log(5555)
        that.getCardList()
        // my.showModal({
        //   content: res.data.data.msg,
        //   showCancel: false,
        //   confirmText: '我知道了',
        //   confirmColor: '#ff5151',
        //   success(e) {}
        // })
      }
    }).catch(err => {
      console.log(err)
      my.showToast({
        content: '服务器错误',
        type: 'exception',
      })
    })
  },
  startOpenCard(templateid, appid, openid) {
    const that = this;
    var plugin = requirePlugin("alipassToolKit") // 引用名称需与 app.json 中定义名称相同 
    var outstringObj = {
      orgcode: '1111061',
      cardnumber: '',
      scene: 'miniProgram',
    };

    let params = {
      cardParams: { //开卡入参，
        templateId: templateid, // 开卡的卡模板ID
        templateAppId: appid, // 卡模板ID 所关联的 AppId
        outString: JSON.stringify(outstringObj), // 外部参数商家自定义透传信息
        pageType: 'half', //默认是 half

      },
      callback: function (res) {
        console.log('======8888', res)
        // {resultCode: '10000', notificationName: 'NEBULANOTIFY_AliPassApplyCardCallback', resultMsg: '用户领卡成功', NBPageUrl: 'https://2021005136696526.hybrid.alipay-eco.com/index.html#pages/index/index', success: true}
        if (res.resultCode === 10000 || res.success === true) {
          // my.showToast({ content: '开卡成功' });
          that.applyVirtual()
        }
      }
    }
    plugin.openCard(params); // 接口参数说明如下

  },
   //客服电话
   phone() {
    my.makePhoneCall({
      number: '4000242289',
    })
  },
  applyCard() {
    const that = this;
    let data = {
      phone_sign: '',
      phone: that.data.phone,
      channel: 'zfb'
    }
    myRequest.EasyHttp.post(api.reqUrls.applyVirtualCard, data).then(res => {
      if (res.data.status == 1) {
        // my.showToast({
        //   content: res.data.msg,
        //   type: 'success',
        // })

        that.bindCardNumber(res.data.result.member_list[0].cardnumber)
      } else {
        my.hideLoading();
        my.showModal({
          showCancel: false,
          content: res.data.msg,
          success(res) {
            if (res.confirm) {

            }
          }
        })
      }
    })
  },
  getCardList() {
    const that = this;
    let data = {
      appid: my.getAppIdSync().appId,
      openId: my.getStorageSync({
        key: 'openId'
      }).data
    }
    myRequest.EasyHttp.post(api.reqUrls.getAlipayMemberCardBindStatus, data).then(res => {

      my.hideLoading();
      if (res.data.data.isbindmembercard === true) {
        my.showModal({
          content: '绑定成功',
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {
            that.getCardinfoData()
          }
        })
      } else {
        let stringArray = res.data.data.cards.map(item => `${item.cardnumber} 余额￥${item.totalamount}`);
        // 弹出选择卡号对话框
        my.optionsSelect({
          title: "选择绑定卡号",
          optionsOne: stringArray,
          positiveString: "立即绑定",
          negativeString: "绑定其他储值卡",
          success(prop) {
            if (prop.selectedOneIndex !== "") {
              console.log(123)
              let cardnumber = res.data.data.cards[prop.selectedOneIndex].cardnumber
              that.bindCardNumber(cardnumber)
            } else {
              that.setData({
                phoneToggle: true
              })
            }
          }
        });
      }


    })
  },
  bindCardNumber(cardNumber, way = '') {
    const that = this;
    let data = {
      appid: my.getAppIdSync().appId,
      openId: my.getStorageSync({
        key: 'openId'
      }).data,
      cardnumber: cardNumber,
      way: way ? way : 3,
      phone: that.data.phone,
      checkcode: that.data.smsCode,
    }
    myRequest.EasyHttp.post(api.reqUrls.alipayMemberCardBind, data).then(res => {
      my.hideLoading();
      console.log(res, 787878)
      if (res.data.data.success) {
        my.showModal({
          content: '绑卡成功',
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {
            that.getCardinfoData()
          }
        })
      } else {
        my.showToast({
          content: res.data.data.msg,
          type: 'exception',
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const that = this;
    login.checkLogin().then(res => {
      that.getVipMsg()
    }).catch(err => {
      app.appCallBack = (e) => {
        that.getVipMsg()
      }
    })
  },
  getVipMsg() {
    const that = this;
    const refresh = my.getStorageSync({
      key: 'refresh'
    }).data;
    const isVip = my.getStorageSync({
      key: 'isVip'
    }).data;
    const isfoundingmember = my.getStorageSync({
      key: 'isfoundingmember'
    }).data;
    const cardnumber = my.getStorageSync({
      key: 'cardnumber'
    }).data;
    const totalamount = my.getStorageSync({
      key: 'totalamount'
    }).data;
    const userName = my.getStorageSync({
      key: 'userName'
    }).data;
    const userPhone = my.getStorageSync({
      key: 'userPhone'
    }).data;
    if (isVip) {
      if (refresh) {
        that.getCardinfoData()
      } else {
        that.setData({
          cardnumber,
          isVip,
          isfoundingmember,
          totalamount,
          userName,
          userPhone
        })
        that.getRefreshMember()
      }
    } else {
      that.setData({
        cardnumber,
        isVip,
        isfoundingmember,
        totalamount,
        userName,
        userPhone
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    const that = this;
    that.onCloseToggle()
    that.onClosePhoneToggle()
    clearTimeout(timeOut)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    const that = this;
    that.onCloseToggle()
    that.onClosePhoneToggle()
    clearTimeout(timeOut)

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    const that = this;
    that.onCloseToggle()
    that.onClosePhoneToggle()
    that.getCardinfoData()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})